package cn.itcast.Rainbow_self_mention.Activity;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.itcast.Rainbow_self_mention.R;
import cn.itcast.Rainbow_self_mention.Server.MapServer;
import cn.itcast.Rainbow_self_mention.Server.OrderServer;
import cn.itcast.Rainbow_self_mention.Dao.SqlHelper;

public class Order extends Activity {
    public ImageView home, order, lowmap, mine;//底部一栏按钮
    EditText name, number, name_of_good;//收件人姓名，电话，物品名称
    Button map, photo, sure;
    ImageView imageView;
    ListView lv;
    SqlHelper hp=new SqlHelper(this);
    RelativeLayout all;
    ImageButton take;
    String imagename, time, imagepath;
    Uri imageuri;
    AlertDialog dialog;
    adapter ad = new adapter();

    FirstServiceConn firstconn;
    OrderServer.Sender sender;
    static String sentresult,boxname=null;
    static Boolean link = false;
    String[] Title;
    int[] box_id;
    Double[] distance;
    SimpleDateFormat gettimetools = new SimpleDateFormat("yyyyMMddHHmmss");
    int userid,boxid;

    static MapServer.sender msender;
    MyServiceConn conn;
    class MyServiceConn implements ServiceConnection { //用于实现连接服务
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            msender = (MapServer.sender) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }
    class FirstServiceConn implements ServiceConnection { //用于实现连接服务
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            sender = (OrderServer.Sender) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    class W extends Thread{
        @Override
        public void run() {
            super.run();
            threadwait(2);
        }
    }
    public void threadwait(int time) {
        try {
            Thread.sleep(time * 1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.low_order);

        Intent server = new Intent(this, OrderServer.class); //创建意图对象
        firstconn = new FirstServiceConn();//创建服务连接对象
        bindService(server, firstconn, BIND_AUTO_CREATE);

        Intent server2 = new Intent(this,MapServer.class); //创建意图对象
        conn = new MyServiceConn();//创建服务连接对象
        bindService(server2, conn, BIND_AUTO_CREATE);

        SQLiteDatabase db = hp.getReadableDatabase();
        Cursor cursor = db.query("logined", new String[]{"userid"}, "_id=?", new String[]{"1"}, null, null, null);
        cursor.moveToFirst();
        userid = cursor.getInt(cursor.getColumnIndex("userid"));
        db.close();
        cursor.close();

    }

    @Override
    protected void onResume() {
        super.onResume();
        init();
        initbutton();
        buildlist();
    }

    public void init() {
        home = findViewById(R.id.deposit_homepage);
        order = findViewById(R.id.deposit_deposit);
        lowmap = findViewById(R.id.deposit_map);
        mine = findViewById(R.id.deposit_my);
        name = findViewById(R.id.deposit_account);
        number = findViewById(R.id.deposit_number);
        map = findViewById(R.id.deposit_choosemap);
        photo = findViewById(R.id.deposit_photo);
        imageView = findViewById(R.id.deposit_takephoto);
        sure = findViewById(R.id.deposit_sure);
        name_of_good = findViewById(R.id.name_of_good);
        take = new ImageButton(this);

    }

    public void initbutton() {
        map.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder;
                all = new RelativeLayout(Order.this);
                all.setBackgroundResource(R.drawable.shape5);
                all.getBackground().setAlpha(100);
                RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT
                        , RelativeLayout.LayoutParams.WRAP_CONTENT);
                params1.addRule(RelativeLayout.CENTER_IN_PARENT );
                all.addView(lv, params1);
                //all.addView(choose, params2);
                builder = new AlertDialog.Builder(Order.this).setView(all);
                dialog = builder.create();
                dialog.show();
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        all.removeAllViews();
                    }
                });
            }
        });
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Order.this, Home.class);
                startActivity(intent);
                overridePendingTransition(0, 0);
            }
        });
        order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onResume();
            }
        });
        lowmap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Order.this, Map.class);
                startActivity(intent);
                overridePendingTransition(0, 0);
            }
        });
        mine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Order.this, Personal.class);
                startActivity(intent);
                overridePendingTransition(0, 0);
            }
        });
        take.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    check();
                    dialog.dismiss();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder;
                all = new RelativeLayout(Order.this);
                all.setBackgroundResource(R.drawable.shape5);
                all.getBackground().setAlpha(100);
                RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT
                        , RelativeLayout.LayoutParams.WRAP_CONTENT);
                params1.addRule(RelativeLayout.CENTER_IN_PARENT );
                take.setBackgroundResource(R.drawable.camera);
                all.addView(take, params1);
                builder = new AlertDialog.Builder(Order.this).setView(all);
                dialog = builder.create();
                dialog.show();
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        all.removeAllViews();
                    }
                });

            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int i=0;
                W w=new W();
                w.start();
               if(name_of_good.getText().toString().equals(""))
               {
                   name_of_good.setHint("请输入物品名称");
                   name_of_good.setHintTextColor(getResources().getColor(R.color.red));
                   i++;
               }
                if(number.getText().toString().equals(""))
                {
                    number.setHint("请输入收件人电话号码");
                    number.setHintTextColor(getResources().getColor(R.color.red));
                    i++;
                }
                if(imagename==null)
                {
                    all=new RelativeLayout(Order.this);
                    AlertDialog dialog;
                    AlertDialog.Builder builder;
                    TextView t=new TextView(Order.this);
                    t.setText("请拍摄物品图片");
                    t.setTextSize(40);
                    RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT
                            , RelativeLayout.LayoutParams.WRAP_CONTENT);
                    params2.addRule(RelativeLayout.CENTER_IN_PARENT);
                    all.addView(t,params2);

                    builder = new AlertDialog.Builder(Order.this).setView(all);
                    dialog = builder.create();
                    dialog.show();
                    dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            all.removeAllViews();
                        }
                    });
                    i++;
                }
                if(boxname==null)
                {
                    map.setText("请选择地址");
                    map.setTextColor(getResources().getColor(R.color.red));
                    i++;
                }
                if(String.valueOf(boxid).equals(null))
                {i++;}
                if (i==0)
                {
                    sender.send_order(userid,name_of_good.getText().toString(),number.getText().toString(),imagename,time,boxid,imagepath);
                    Intent intent=new Intent(Order.this,For_Upload_Order.class);
                    startActivityForResult(intent,3);
                    overridePendingTransition(0, 0);
                }

            }
        });
    }


public void buildlist(){
        lv=new ListView(this);
        initsource();
}
    public void initsource() {
        SQLiteDatabase db;
        db = hp.getReadableDatabase();
        Cursor cursor = db.query("box", new String[]{"box_id", "location", "distance"},
                null, null, null, null, null);
        cursor.moveToFirst();
        if (cursor.getCount() > 0) {
            Title = new String[cursor.getCount()];
            box_id = new int[cursor.getCount()];
            distance = new Double[cursor.getCount()];
            for (int i = 0; i < cursor.getCount(); i++) {

                Title[i] = cursor.getString(cursor.getColumnIndex("location"));
                box_id[i] = cursor.getInt(cursor.getColumnIndex("box_id"));
                distance[i] = cursor.getDouble(cursor.getColumnIndex("distance"));
                cursor.moveToNext();
            }
            db.close();
            cursor.close();
            initalllistview();
        } else {
            Title = new String[0];
            box_id = new int[0];
            distance = new Double[0];

        }
    }
    public void initalllistview() {
        if (Title.length > 0) {
            ad.SetListview(lv);
            ad.SetOnclicklistener(lv);

        }
    }
    class adapter extends BaseAdapter {
        public ViewHolder holder;


        public void SetOnclicklistener(ListView lv) {
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    boxid=box_id[position];
                    boxname=Title[position];
                    map.setText(boxname);
                    dialog.dismiss();

                }
            });
        }

        public void SetListview(ListView lv) {
            lv.setAdapter(this);
        }

        @Override
        public int getCount() {
            return Title.length;
        }

        public Object getItem(int position) {
            return Title[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {

                convertView = View.inflate(Order.this, R.layout.item_of_map, null);

                holder = new ViewHolder();
                holder.Title = (TextView) convertView.findViewById(R.id.title);
                holder.Range = (TextView) convertView.findViewById(R.id.range);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.Title.setText(Title[position]);
            holder.Range.setText(distance[position] + "米");
            return convertView;
        }
    }

    static class ViewHolder {

        TextView Title;
        TextView Range;


    }

    public void check() throws IOException {//判断是否给了相机权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {

            dotake();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        }

    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {//检验权限
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                try {
                    dotake();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(this, "没有摄像头权限", Toast.LENGTH_LONG).show();
            }
        }

    }

    public void dotake() throws IOException {//拍照动作
        File file = new File(getExternalCacheDir(), "imageout.png");
        if (file.exists()) {
            file.delete();
        } else {
            file.createNewFile();
        }
        imageuri = FileProvider.getUriForFile(this, "Rainbow_self_mention", file);
        Intent intent = new Intent();
        intent.setAction("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri);
        startActivityForResult(intent, 1);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {//相机拍完照之后，或是选择完相片过之后，返回时会回传请求码，根据请求码的不同，获取照片的方式也不同
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {//获取相机照片
                try {
                    InputStream input = getContentResolver().openInputStream(imageuri);
                    Bitmap bitmap = BitmapFactory.decodeStream(input);
                    imageView.setImageBitmap(bitmap);
                    saveImageToGallery(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }

        else if (requestCode==3)
        {
            if(resultCode==1)
            {
                finish();
            }

        }

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)


    public int saveImageToGallery(Bitmap bmp) {
        String root = Environment.getExternalStorageDirectory().getAbsolutePath();
        String dirName = "MTZTG";
        File appDir = new File(root, dirName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        long timeStamp = System.currentTimeMillis();
        time = gettimetools.format(new Date(timeStamp));
        String fileName = userid + time + ".png";
        File file = new File(appDir, fileName);
        imagename = file.getName();
        imagepath = file.getPath();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            Order.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.fromFile(new File(file.getPath()))));
            return 2;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return -1;
    }

    public static Handler handler = new Handler() {//创建消息处理器对象
        //在主线程中处理从子线程发送过来的消息
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            sentresult = bundle.getString("sentresult");
            if (sentresult.equals("网络连接错误")) {
                link = false;
            }
            if (sentresult.equals("网络连接成功")) {
                link = true;
            }

        }
    };
}
